package jehc.cloud.common.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import org.apache.commons.codec.binary.Base64;
import javax.imageio.ImageIO;
/**
 * @Desc Base64Util
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class Base64Util {
    /**
     * 编码
     * @param byteArray
     * @return
     */
    public static String encode(byte[] byteArray) {
        return new String(new Base64().encode(byteArray));
    }

    /**
     * 解码
     * @param base64EncodedString
     * @return ss
     */
    public static byte[] decode(String base64EncodedString) {
        return new Base64().decode(base64EncodedString);
    }


    /**
     *
     * @param imgPath
     * @return
     */
    public static String imgToBase64ByLocal(File imgPath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;

        // 读取图片字节数组
        try {
            in = new FileInputStream(imgPath);

            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);
        base64Str.replaceAll("(\r\n|\r|\n|\n\r)", "");//替换base64后的字符串中的回车换行
        return base64Str;// 返回Base64编码过的字节数组字符串
    }

    /**
     * 本地转
     * @param imgPath
     * @return
     */
    public static String imgToBase64ByLocal(String imgPath){
        return imgToBase64ByLocal(new File(imgPath));
    }

    /**
     * 在线转
     * @param imgUrl
     * @return
     */
    public static String imgToBase64Http(String imgUrl) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgUrl);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray());
    }

    /**
     *
     * @param imgStr
     * @param imgFilePath
     * @return
     */
    public static boolean Base64ToImage(String imgStr,String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片
        if (StringUtil.isEmpty(imgStr)) // 图像数据为空
            return false;

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr.replace("data:image/png;base64,", ""));
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }

            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     *  根据图片流生成Base64
     * @param bufferedImage
     * @return
     */
    public static String toBase64(BufferedImage bufferedImage){
        String base64 = null;
        if(null == bufferedImage){
            return base64;
        }
        try {
            Integer width = bufferedImage.getWidth();
            Integer height = bufferedImage.getHeight();
            log.info("Width：" + width + ", Height:"+height);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();//输出流
            ImageIO.write(bufferedImage, "png", stream);
            BASE64Encoder encoder = new BASE64Encoder(); // 对字节数组Base64编码
            base64 = encoder.encode(stream.toByteArray());
            System.out.println(base64);
            stream.flush();
            stream.close();
        } catch (IOException e) {
            log.error("生成图片Base64异常：{}",e);
        }
        return base64;
    }

    /**
     * 根据图片流生成Base64
     * @param imageBytes
     * @return
     */
    public static String toBase64(byte[] imageBytes){
        String imageBase64 = null;
        try {
            BASE64Encoder base64Encoder =new BASE64Encoder();
            imageBase64 = "data:png;base64," + base64Encoder.encode(imageBytes);
            imageBase64 = imageBase64.replaceAll("[\\s*\t\n\r]", "");
            return imageBase64;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }
}
